package com.storyroad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.storyroad.utils.DBConnection;
import com.storyroad.utils.TableNames;

/**
 * Servlet implementation class BanUser
 */
public class BanUser extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BanUser() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * Puts a ban on the specified registered user. Ban on a user account lasts for 30 days. Only the admin is allowed to
	 * carry out this operation.
	 * @param request HttpServletRequest object that contains data coming from front-end
	 * @param response HttpServletResponse object that contains data which is prepared after processing the incoming data
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String username;
		String banUsername;
		String f_requestType = request.getParameter("request_type");
		Connection conn = new DBConnection().connect();
		PrintWriter out = response.getWriter();
		PreparedStatement stmt = null;

		if (f_requestType == null || !f_requestType.equals("Android")) {
			f_requestType = "Web";
			username = (String) request.getSession().getAttribute("username");
			// If it is not a valid username, redirect to the login page.
			if (username == null) {
				response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/LoginPage.jsp"));
				return;
			}
		} else {
			username = request.getParameter("username");
		}

		// Check whether this action is performed by the admin. If not, terminate operation and return an error message.
		if (username == null || !username.equals("admin")) {
			out.print("You are not allowed to do this!");
			return;
		}

		if (conn == null) {
			out.println("Connection error");
		} else {
			try {
				java.util.Date today;
				Timestamp timeStamp;
				Calendar cal;
				banUsername = request.getParameter("banUsername");
				today = new java.util.Date();
				timeStamp = new Timestamp(today.getTime());
				cal = Calendar.getInstance();
				cal.add(Calendar.DAY_OF_WEEK, 30);
				timeStamp.setTime(cal.getTime().getTime());
				/*
				 * Date that is inserted to the table is 30 days from the start of the ban. This makes it easier to check
				 * whether the ban on user is removed or not. Ban check is carried out whenever the user tries to log on
				 * to the system.
				 */
				stmt = conn.prepareStatement("INSERT INTO "
						+ TableNames.BANNED_USER_TABLE
						+ " (username,date) VALUES (?,?)");
				stmt.setString(1, banUsername);
				stmt.setTimestamp(2, timeStamp);

				int databaseResponse = stmt.executeUpdate();
				boolean banSuccess = false; // as default

				if (databaseResponse == 1) {
					banSuccess = true;
				} else {
					banSuccess = false;
				}

				request.setAttribute("banSuccess", banSuccess);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				out.print(e.getMessage());
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
